package com.iafme.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iafme.constants.CodeConstants;
import com.iafme.dto.req.RedemptionReqDTO;
import com.iafme.mapper.RedemptionMapper;
import com.iafme.model.Redemption;
import com.iafme.service.RedemptionService;
import com.iafme.utils.AdmissionNumUtil;
import com.systemframework.constants.Constants;
import com.systemframework.exception.ResultException;
import com.systemframework.redis.RedisCache;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author summer
 * @version 1.0
 * @date 2025/4/15 15:11
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class RedemptionServiceImpl extends ServiceImpl<RedemptionMapper, Redemption> implements RedemptionService {

    private final RedisCache redisCache;

    @Override
    public void saveRedemption(RedemptionReqDTO redemptionReqDTO) {
        List<Redemption> list= ListUtil.list(true);
        Integer codeNum = redemptionReqDTO.getCodeNum();
        for (int i = 0; i < codeNum; i++) {
            Redemption redemption = new Redemption();
            redemption.setCode(AdmissionNumUtil.redemptionNum());
            redemption.setStatus(Constants.ZERO);
            list.add(redemption);
            redisCache.set(CodeConstants.REDEMPTION_NUM_PREFIX+redemption.getCode(),redemption.getCode(),  7, TimeUnit.DAYS);
        }
        this.saveBatch(list);
    }

    @Override
    public void updateRedemptionStatus(RedemptionReqDTO redemptionReqDTO) {
        LambdaQueryWrapper<Redemption> eq = Wrappers.lambdaQuery(Redemption.class).eq(Redemption::getCode, redemptionReqDTO.getCode());
        Redemption redemption = this.getOne(eq);
        redemption.setStatus(redemptionReqDTO.getStatus());
        this.updateById(redemption);
    }

    @Override
    public void checkRedemption(String code) {
        LambdaQueryWrapper<Redemption> eq = Wrappers.lambdaQuery(Redemption.class).eq(Redemption::getCode, code);
        Redemption redemption = this.getOne(eq);
        if(ObjectUtil.isEmpty(redemption)){
            throw new ResultException("兑换码不存在");
        }

        if(redemption.getStatus().equals(Constants.ONE)){
            throw new ResultException("兑换码已被使用");
        }
        if (redemption.getStatus().equals(Constants.TWO)){
            throw new ResultException("兑换码已过期");
        }
        redemption.setStatus(Constants.ONE);
        this.updateById(redemption);
    }
}
